package com.jjyd.crlp.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.jjyd.crlp.domain.entity.UserAuth;
import com.jjyd.crlp.domain.entity.Users;
import com.jjyd.crlp.model.base.ResultModel;
import com.jjyd.crlp.model.code.CommonConst;
import com.jjyd.crlp.model.dto.login.LoginDto;
import com.jjyd.crlp.services.LoginService;
import com.jjyd.crlp.util.check.CheckUtil;
import com.jjyd.crlp.util.encryption.MD5Util;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * 用户登陆
 */
@RestController
@RequestMapping("/login")
@Api(description = "用户登陆接口")
public class LoginController {

    @Autowired
    private LoginService loginService;

    /**
     * 登陆接口
     * @param loginDto
     * @return
     */
    @PostMapping("")
    @ApiOperation(value = "用户登陆接口")
    public ResultModel<String> login(LoginDto loginDto) {
        String md5 = MD5Util.changeMD5(loginDto.getPassword());
        loginDto.setPassword(md5);
        UserAuth userAuth = loginService.login(loginDto);
        CheckUtil.check("用户不存在", userAuth != null);
        Users userInfo = loginService.getUserInfo(userAuth.getUserId());
        
        String key = CommonConst.PARAM_DIGEST;
        Algorithm alg = Algorithm.HMAC256(key);
        
        Date currentTime = new Date();
        String token = JWT.create()
                .withIssuer(CommonConst.ISSUER)
                .withSubject(userAuth.getUserId().toString()) // 用户身份标识 用户的id
                .withAudience(CommonConst.AUDIENCE) // 用户单位
                .withIssuedAt(currentTime) // 签发时间
                .withExpiresAt(new Date(currentTime.getTime() + CommonConst.TIME)) // 一天有效期
                .withJWTId(userAuth.getId().toString()) // 分配JWT的ID
                //.withClaim("PublicClaimExample", "You should not pass!") // 定义公共域信息
                .sign(alg);
        System.out.println(token);

        return new ResultModel<>(token);
    }
}
